﻿using MongoDB.Bson;
using MongoDB.Driver;
using Sustainalytics.Entities;
using System;
using System.Linq;

namespace Sustainalytics.DataLayer
{
    public class MostActiveReportRepository : IMostActiveReportRepository
    {
        private MongoClient _client { get; set; }
        private IMongoDatabase _database { get; set; }

        /// <summary>
        /// Ctor.
        /// </summary>
        public MostActiveReportRepository(string connectionString)
        {
            // DB address
            MongoUrl mongoUrl = MongoUrl.Create(connectionString);

            if (string.IsNullOrWhiteSpace(mongoUrl.DatabaseName))
            {
                throw new ArgumentException("No database specified in the connection string!");
            }

            // Mongo DB client
            _client = new MongoClient(mongoUrl);

            // Mongo DB
            _database = _client.GetDatabase(mongoUrl.DatabaseName);
        }

        public void RecordReportActivity(MostActiveReport report)
        {
            var collection = _database.GetCollection<MostActiveReport>(typeof(MostActiveReport).Name);

            collection.FindOneAndUpdate(
                Builders<MostActiveReport>.Filter.Eq(x=> x.Id, report.Id),
                Builders<MostActiveReport>.Update
                    .Inc(f => f.NumberOfDownloads, 1)
                    .Set(f => f.LastUpdated, new BsonDateTime(DateTime.Now))
                    .Set(f => f.CompanyName, report.CompanyName)
                    .Set(f => f.CompanyNameUrlFriendly, report.CompanyNameUrlFriendly)
                    .Set(f => f.MainExchange, report.MainExchange)
                    .Set(f => f.MainTicker, report.MainTicker)
                    .Set(f => f.UniverseIds, report.UniverseIds)
                    .Set(f => f.ReportType, report.ReportType));

            collection.Indexes.CreateOne(Builders<MostActiveReport>.IndexKeys.Ascending(x => x.CompanyName), new CreateIndexOptions { Unique = true });
        }
    }
}
